<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
    
      <el-form-item label="产品型号" prop="type">
        <!-- <el-tree-select
          v-model="formData.type"
          :data="menuTree"
          :default-expanded-keys="[0]"
          :props="defaultProps"
          check-strictly
          node-key="id"
        /> -->
        <el-select v-model="formData.type" :disabled="isUpdate" placeholder="请选择">
          <el-option
            v-for="(item, index) in menuTree"
            :key="index"
            :label="item"
            :value="item"
          />
    </el-select>
      </el-form-item>
      
      <!-- <el-form-item label="物料" prop="name">
        <el-tree-select 
          v-model="formData.parentId"
          :data="menuTree"
          :default-expanded-keys="[0]"
          :props="defaultProps"
          check-strictly
          node-key="id"
        />
      </el-form-item> -->

      <el-form-item label="阈值最小值" prop="lowerWeight">
        <el-input v-model="formData.lowerWeight" clearable placeholder="请输入最小值"/>
      </el-form-item>
      <el-form-item label="阈值最大值" prop="upperWeight">
        <el-input v-model="formData.upperWeight" clearable placeholder="请输入最大值" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as weightRulesApi from '@/api/hcxly/materialWeightRules/Index'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'

defineOptions({ name: 'weightRulesForm' })

const { wsCache } = useCache()
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  type: '',
  lowerWeight: '',
  upperWeight: ''
})
const formRules = reactive({
  type: [{ required: true, message: '产品型号不能为空', trigger: 'blur' }],
  lowerWeight: [{ required: true, message: '阈值最小值不能为空', trigger: 'blur' }],
  upperWeight: [{ required: true, message: '阈值最大值不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const isUpdate = ref(true)

/** 打开弹窗 */
const open = async (type: string, id?: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  if(type === 'create'){
    isUpdate.value = false
  } else{
    isUpdate.value = true
  }
  
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await weightRulesApi.getMaWeight(id)
    } finally {
      formLoading.value = false
    }
  }
  // 获得菜单列表
  await getTree('')
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  if(formData.value.lowerWeight >= formData.value.upperWeight) return

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as weightRulesApi.MaWeightRulesVO
    console.log(data)
    await weightRulesApi.createMaWeightRules(data)
    if (formType.value === 'create') {
      message.success(t('common.createSuccess'))
    } else {
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
    // 清空，从而触发刷新
    wsCache.delete(CACHE_KEY.ROLE_ROUTERS)
  }
}

/** 获取下拉框[上级菜单]的数据  */
const menuTree = ref([]) // 树形结构
const getTree = async (proType) => {
  // menuTree.value = []
  menuTree.value = await weightRulesApi.getProductModel(proType)
  console.log(menuTree.value)
  // let menu: Tree = { id: 0, name: '主类目', children: [] }
  // menu.children = handleTree(res)
  // menuTree.value.push(menu)deleteMaWeightRules
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
  type: '',
  lowerWeight: '',
  upperWeight: ''
  }
  formRef.value?.resetFields()
}

</script>
